import { useRequest } from "ahooks";
import { useState } from "react";

interface IClockOptions<T> {
  onSuccess: (data: T) => void;
  onError?: (error: unknown) => void;
  maxErrorCount?: number;
}

export const useClock = <T>(
  fetch: () => Promise<T>,
  options: IClockOptions<T>,
) => {
  const { onSuccess, onError, maxErrorCount = 5 } = options;

  const [errorCount, setErrorCount] = useState(() => 0);

  const { run } = useRequest(
    async () => {
      if (errorCount >= maxErrorCount) return;

      return await fetch();
    },
    {
      manual: true,
      onSuccess: (response) => {
        if (!response) return;

        return onSuccess(response);
      },
      onError: (error) => {
        console.error("Clock fetch error:", error);
        setErrorCount((prevCount) => prevCount + 1);

        return onError?.(error);
      },
    },
  );

  return {
    run,
    errorCount,
  };
};
